from concurrent.futures import ThreadPoolExecutor
import FileTools
import _const
import config
from apk_info import apk_info
from apk_workshop import apk_workshop
#
# @author xuyan
#
class apk_factory:

    _apks = []
    _task = {}
    _executor = None

    def __init__(self, *args, **kwargs):
        self._executor = ThreadPoolExecutor(max_workers=5)

    @classmethod
    def get_instance(cls, *args, **kwargs):
        if not hasattr(apk_factory, '_instance'):
            apk_factory._instance = apk_factory(*args, **kwargs)

        return apk_factory._instance

    #添加工作组件集合
    def setApks(self,apks):
        self._apks.extend(apks)
        return self

    #添加工作组件
    def addApk(self,apk):
        self._apks.append(apk)
        return self

    #开启工作
    def start(self):
        if self._apks.count == 0:
            raise ValueError("apks 工作组件数量为0")
        #创建任务
        for info in self._apks:
            if not info.apk_path in self._task:
                task = self._executor.submit(self._arrange_task,info)
                self._task[info.apk_path] = task

    #安排车间处理apk任务
    def _arrange_task(self,apk_info):
        workshop = apk_workshop(apk_info.apk_path,apk_info.apk_type,apk_info.config_xml,apk_info.apk_signer_jks,apk_info.work_out)
        workshop.start()


if __name__ == '__main__':
    factory = apk_factory.get_instance()
    #0：学生端 1：教师端
    work_type = 0
    apk_path = _const.apkPath_student
    if work_type == 1:
        apk_path = _const.apkPath_teacher
    apkList = FileTools.readFile(apk_path)
    for i,apk in enumerate(apkList):
        factory.addApk(apk_info(apk,work_type))
    factory.start()
